<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <link rel="stylesheet" href="/layui/css/layui.css">
</head>
<body>
<form class="layui-form" style="margin-top: 10px;margin-left: 10px">
    登录名：
    <div class="layui-inline">
        <input class="layui-input" name="loginName" placeholder="登录名" autocomplete="off">
    </div>
    <button class="layui-btn" lay-submit lay-filter="selectConditionFilter" data-type="reload">搜索</button>
    <button class="layui-btn layui-btn-primary" type="reset" id="resetButton">重置</button>
</form>
<!--列表显示-->
<table id="userTable" lay-filter="userFilter"></table>
<!--行编辑工具栏-->
<script type="text/html" id="barRowEdit">
    <button class="layui-btn layui-btn-xs layui-btn-normal" lay-event="resetPassword">重置密码</button>
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<!--头部工具栏-->
<script type="text/html" id="toolbarHead">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add">添加</button>
        <button class="layui-btn layui-btn-sm" lay-event="delete">删除</button>
        <button class="layui-btn layui-btn-sm" lay-event="update">编辑</button>
    </div>
</script>

<!--用户添加form-->
<form id="userAddForm" class="layui-form" style="display: none"> <!-- 提示：如果你不想用form，你可以换成div等任何一个普通元素 -->
    <div class="layui-form-item">
        <label class="layui-form-label">用户名称</label>
        <div class="layui-input-block">
            <input type="text" name="loginName" placeholder="请输入" required  lay-verify="required" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-block">
            <input type="text" name="password" placeholder="请输入密码" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">真实姓名</label>
        <div class="layui-input-block">
            <input type="text" name="userName" placeholder="请输入真实姓名" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">邮箱</label>
        <div class="layui-input-block">
            <input type="email" name="email" placeholder="请输入邮箱" required lay-verify="email" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">手机号</label>
        <div class="layui-input-block">
            <input type="tel" name="phonenumber" placeholder="请输入手机号" required-phone lay-verify="required|phone|number" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">部门</label>
        <div class="layui-input-block">
            <select name="deptId">
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">状态</label>
        <div class="layui-input-block">
            <input type="checkbox" checked="" name="status" lay-skin="switch" lay-filter="switchTest" lay-text="正常|失效">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">性别</label>
        <div class="layui-input-block">
            <input type="radio" name="sex" value="0" title="男" checked="">
            <input type="radio" name="sex" value="1" title="女">
        </div>
    </div>
    <div class="layui-form-item" pane="">
        <label class="layui-form-label">角色</label>
        <div class="layui-input-block" id="addRoleCheckBox" name="roles">

        </div>
    </div>


    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="userAddFilter">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>


<!--用户更新form-->
<form id="userUpdateForm" class="layui-form" lay-filter="userUpdateFilter" style="display: none"> <!-- 提示：如果你不想用form，你可以换成div等任何一个普通元素 -->
    <input type="hidden" name="userId">
    <input name="userId" hidden="hidden"/>
    <div class="layui-form-item">
        <label class="layui-form-label">登录名</label>
        <div class="layui-input-block">
            <input type="text" name="loginName" placeholder="请输入登录名" readonly required lay-verify="required"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">真实姓名</label>
        <div class="layui-input-block">
            <input type="text" name="userName" placeholder="请输入真实姓名" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">邮箱</label>
        <div class="layui-input-block">
            <input type="email" name="email" placeholder="请输入邮箱" required lay-verify="email" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">手机号</label>
        <div class="layui-input-block">
            <input type="tel" name="phonenumber" placeholder="请输入手机号" required lay-verify="required|phone|number" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">部门</label>
        <div class="layui-input-block">
            <select id="deptSelect" name="deptId">
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">状态</label>
        <div class="layui-input-block">
            <input type="checkbox" name="status" id="updateStatus" lay-skin="switch" lay-filter="switchTest"
                   lay-text="正常|失效">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">性别</label>
        <div class="layui-input-block">
            <input type="radio" name="sex" value="0" title="男" checked="">
            <input type="radio" name="sex" value="1" title="女">
        </div>
    </div>
    <input hidden name="updateBy" th:value="${session.username}">
    <div class="layui-form-item" pane="">
        <label class="layui-form-label">角色</label>
        <div class="layui-input-block" name="roles" id="updateRoleCheckBox">

        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">头像</label>
        <input type="hidden" name="avatar" id="avatar">
        <div class="layui-input-block">
            <button type="button" class="layui-btn" id="uploadFile">
                <i class="layui-icon">&#xe67c;</i>上传图片
            </button>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="updateUserFilter">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<!--重置密码-->
<form class="layui-form" action="" id="resetPasswordForm" lay-filter="resetPasswordFormFilter"
      style="display: none;margin-right: 40px;margin-top: 20px">
    <!--用户id-->
    <input name="userId" hidden="hidden"/>
    <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-block">
            <input type="text" name="password" placeholder="请输入密码" required lay-verify="required" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="userUpdateFilter">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<!--js 代码-->
<script src="/layui/layui.js"></script>
<script>
    layui.use(['table','layer','jquery','form','upload'], function() {
        let table = layui.table;
        let layer = layui.layer;
        let $ = layui.jquery;
        var form = layui.form;
        var upload = layui.upload;
        var uploadInst = upload.render({
            elem: '#uploadFile' //绑定元素
            , url: '/user/uploadHeadPic' //上传接口
            , auto: true // 选择文件后自动上传
            , field: "headPic"
            , done: function (res) {
                // layer.msg(JSON.stringify(res));
                //上传完毕回调
                if (res.code == 0) {
                    $("#avatar").val(res.data.filePath);
                }
            }
            , error: function () {
                //请求异常回调
            }
        });
        //用户列表js
        let userTable = table.render({
            elem: '#userTable'
            , toolbar: '#toolbarHead'
            , url: '/user/queryAll' //数据接口
            , page: true //开启分页
            , cols: [
                [ //表头
                    {type: 'checkbox', fixed: 'left'}
                    , {field: 'userId', title: '编号', width: 80, sort: true}
                    , {field: 'loginName', title: '登录名', width: 100}
                    , {field: 'userName', title: '真实姓名', width: 120}
                    , {field: 'email', title: '邮箱', width: 160}
                    , {field: 'phonenumber', title: '手机号', width: 160}
                    , {
                    field: 'sex', title: '性别', width: 80, templet: function (d) {
                        if (d.sex === "0") {
                            return '男'
                        } else {
                            return '女'
                        }
                    }
                }
                    , {field: 'status', title: '状态', width: 80, toolbar: "#userState"}
                    , {field: 'deptName', title: '部门名称', width: 100}
                    , {field: 'createBy', title: '创建人', width: 100}
                    , {field: 'createTime', title: '创建时间', width: 160}
                    , {field: 'updateBy', title: '修改人', width: 100}
                    , {field: 'updateTime', title: '修改时间', width: 160},
                    {fixed: 'right', align: 'center', width: 160, toolbar: '#barRowEdit'}
                ]
            ]
        });

        let $deptSelect = $("select[name=deptId]");
        let $roleCheckBox = $("div[name=roles]");
        let options = '';
        let inputs = '';

        //填充部门下拉框
        $.ajax({
            url: "/user/findAllDept",
            type: "GET",
            dataType: "JSON",
            success: function (allDept) {
                //将数据放到select中
                for (let i = 0; i < allDept.length; i++) {
                    options += '<option value="' + allDept[i].dept_id + '">' + allDept[i].dept_name + '</option>';
                }
                $deptSelect.html(options)
            }
        })
        //填充角色复选框
        $.ajax({
            url: "/user/findAllRole",
            type: "GET",
            dataType: "JSON",
            success: function (allRole) {
                //将数据放到select中
                for (let i = 0; i < allRole.length; i++) {
                    inputs += '<input type="checkbox" name="role" value="' + allRole[i].role_id + '" lay-skin="primary" title="' + allRole[i].role_name + '">'
                }
                $roleCheckBox.html(inputs)
            }
        })
        //条件查询
        form.on('submit(selectConditionFilter)', function (data) {
            console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
            userTable.reload({
                where: { //设定异步数据接口的额外参数，任意设
                    loginName: data.field.loginName
                }
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
        //行编辑工具栏监听事件
        table.on('tool(userFilter)', function (obj) {
            //获取当前行数据
            var data = obj.data;
            //==不匹配类型  1=='1' true      ==== 匹配类型  1==='1' false
            switch (obj.event) {
                case 'resetPassword':
                    //将表单清空
                    document.getElementById("resetPasswordForm").reset();
                    form.val('resetPasswordFormFilter', {
                        userId: data.userId
                    });
                    layer.open({
                        title: '修改密码',
                        type: 1,
                        area: ['500px', '180px'],
                        content: $("#resetPasswordForm"),//这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                    });
                    break;
                case 'del':
                    layer.confirm('真的删除行么', function (index) {
                        $.ajax({
                            url: "/user/deleteById",
                            type: "DELETE",
                            data: {userId: data.userId},
                            dataType: "json",
                            success: function (resp) {
                                if (resp.code == 0) {
                                    layer.msg(resp.msg);
                                    //重新加载数据
                                    userTable.reload();
                                }
                            },
                            error: function (e) {
                                layer.msg("请求失败");
                            }
                        });
                    });
                    break;
                case 'edit':
                    //layer.alert('编辑行：<br>'+ JSON.stringify(data))
                    form.val("userUpdateFilter", data);
                    layer.open({
                        type: 1,
                        area: ['600px', '400px'],
                        content: $('#userUpdateForm') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                    });
                    break;
            }


            //头部工具栏监听事件
            table.on('toolbar(userFilter)', function (obj) {
                let checkStatus = table.checkStatus(obj.config.id);
                let checkData = checkStatus.data;
                switch (obj.event) {
                    case 'add':

                        // layer.msg('添加');
                        //重置form表单
                        // $("#userAddForm").reset();
                        document.getElementById("userAddForm").reset();

                        layer.open({
                            type: 1,
                            area: ['800px', '600px'],
                            content: $('#userAddForm') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                        });
                        break;
                    case 'delete':
                        //layer.msg('删除');
                        //layer.msg(JSON.stringify(checkData));
                        //判断是否选中行
                        if (checkData.length == 0) {
                            layer.msg('请至少选择一行数据');
                            return;
                        }
                        layer.confirm('真的删除行么', function (index) {
                            //获取所有选中行id
                            let userIds = "";
                            for (let i = 0; i < checkData.length; i++) {
                                userIds += checkData[i].userId + ",";
                            }
                            ;
                            userIds = userIds.substr(0, userIds.length - 1);
                            layer.msg(userIds);
                            //调用批量删除
                            $.ajax({
                                url: "/user/deleteByIds",
                                type: "DELETE",
                                data: {userIds: userIds},
                                dataType: "json",
                                success: function (resp) {
                                    if (resp.code == 0) {
                                        layer.msg(resp.msg);
                                        //重新加载数据
                                        userTable.reload();
                                    }
                                },
                                error: function (e) {
                                    layer.msg("请求失败");
                                }
                            });
                        });
                        break;
                    case 'update':

                        if (checkData.length != 1) {
                            layer.msg('编辑只能选中一行');
                            return;
                        }
                        // alert(JSON.stringify(checkData));
                        form.val("userUpdateFilter", checkData[0]);
                        layer.open({
                            type: 1,
                            area: ['800px', '600px'],
                            content: $('#userUpdateForm') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                        });
                        break;
                }
                ;
            });

            //更新监听事件
            form.on('submit(userUpdateFilter)', function (data) {
                layer.msg(JSON.stringify(data.field));
                data.field.role = "";
                let checkedInput = $('input[name=role]:checked');
                for (let i = 0; i < checkedInput.length; i++) {
                    if (i === checkedInput.length - 1) {
                        data.field.role += checkedInput[i].value
                    } else {
                        data.field.role += checkedInput[i].value + ","
                    }
                }
                if (data.field.role === "") {
                    layer.msg("角色不能为空")
                } else {
                    console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
                    //将状态属性的on转换为0，1
                    if (data.field.status === "on") {
                        data.field.status = 0;
                    } else {
                        data.field.status = 1;
                    }
                }
                $.ajax({
                    url: "/user/update",
                    type: "PUT",
                    data: data.field,
                    dataType: "json",
                    success: function (resp) {
                        if (resp.code == 0) {
                            layer.msg(resp.msg);
                            //关闭弹框
                            layer.closeAll('page');
                            //重新加载数据
                            userTable.reload();
                        }
                    },
                    error: function (e) {
                        layer.msg("请求失败");
                    }
                });
                return false;
            });
            //重置密码监听事件
            form.on('submit(userUpdateFilter)', function (data) {
                layer.msg(JSON.stringify(data.field));

                $.ajax({
                    url: "/user/updatePassword",
                    type: "PUT",
                    data: data.field,
                    dataType: "json",
                    success: function (resp) {
                        if (resp.code == 0) {
                            layer.msg(resp.msg);
                            //关闭弹框
                            layer.closeAll('page');
                            //重新加载数据
                            userTable.reload();
                        }
                    },
                    error: function (e) {
                        layer.msg("请求失败");
                    }
                });
                return false;
            });

            //添加监听事件
            form.on('submit(userAddFilter)', function (data) {
                layer.msg(JSON.stringify(data.field));
                if (data.field.role === "") {
                    layer.msg("角色不能为空")
                } else {
                    console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
                    //将状态属性的on转换为0，1
                    if (data.field.status === "on") {
                        data.field.status = 0;
                    } else {
                        data.field.status = 1;
                    }
                }
                $.ajax({
                    url: "/user/insert",
                    type: "POST",
                    data: data.field,
                    dataType: "json",
                    success: function (resp) {
                        if (resp.code == 0) {
                            layer.msg(resp.msg);
                            //关闭弹框
                            layer.closeAll('page');
                            //重新加载数据
                            userTable.reload();
                        }
                    },
                    error: function (e) {
                        layer.msg("请求失败");
                    }
                });
                return false;
            });
        });
    });
</script>
</body>
</html>